package com.itheima.service.impl;


import com.itheima.context.BaseContext;
import com.itheima.mapper.AddressBookMapper;
import com.itheima.pojo.AddressBook;
import com.itheima.service.AddressBookService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {


    @Autowired
    private AddressBookMapper addressBookMapper;


    /**
     * 添加地址
     *
     * @param addressBook
     * @return
     */
    @Override
    public void addAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        addressBookMapper.addAddressBook(addressBook);
    }

    /**
     * 查看所有地址
     *
     * @return
     */
    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = AddressBook.builder().userId(BaseContext.getCurrentId()).build();
        List<AddressBook> addressBooks = addressBookMapper.list(addressBook);
        return addressBooks;
    }

    /**
     * 获取默认地址
     *
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        AddressBook book = AddressBook.builder().userId(BaseContext.getCurrentId())
                .isDefault(1).build();
        AddressBook addressBook = addressBookMapper.getDefaultAddress(book);
        return addressBook;
    }
    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */

    @Override
    @Transactional
    public void updateDefault(AddressBook addressBook) {
        //要设置的默认，根据id修改默认值为1
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        addressBookMapper.updateDefault(addressBook);
        //其它地址都是0

        addressBook.setIsDefault(0);
        addressBookMapper.updateNoDefault(addressBook);
    }
    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {

        AddressBook addressBook=addressBookMapper.getById(id);
        return addressBook;
    }
    /**
     * 根据id修改地址
     * @param addressBook
     * @return
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }
    /**
     * 根据地址id删除地址
     * @return
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }
}